<template>
  <div class="content-wrap info-application" v-loading="loading">
    <div class="content-form tag-scrollbar">
      <template v-if="editable">
        <el-form :model="editForm" :rules="editFormRules" ref="editForm" label-width="0">
          <el-row :gutter="20">
            <el-col :span="24">
              <div class="source-item">
                <div class="star"></div>
                <div class="source-title linear-cyan">标签包</div>
                <div class="source-content">
                  <el-form-item prop="packetId">
                    <el-select
                      v-model="editForm.packetId"
                      multiple
                      filterable
                      placeholder="选择标签包"
                      :disabled="!editable"
                    >
                      <el-option
                        v-for="item in packetList"
                        :key="item.packetId"
                        :label="item.packetNm"
                        :value="item.packetId"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </div>
            </el-col>
            <el-col :span="24">
              <div class="source-item">
                <div class="source-title linear-blue">应用渠道</div>
                <div class="source-content">
                  <el-form-item prop="applicationChannel">
                    <el-select
                      v-model="editForm.applicationChannel"
                      multiple
                      filterable
                      placeholder="选择应用渠道"
                      :disabled="!editable"
                    >
                      <el-option
                        v-for="dict in $dictList('application_channel')"
                        :key="dict.key"
                        :label="dict.value"
                        :value="dict.key.toString()"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </div>
              </div>
            </el-col>
            <el-col :span="24">
              <div class="catalog-item">
                <div class="source-title linear-yellow"><span>标签分类</span></div>
                <div class="source-content">
                  <el-button type="primary" @click="addRule" v-if="!editForm.catalogs.length">添加分类</el-button>
                  <template v-if="editForm.catalogs.length">
                    <el-row class="title">
                      <el-col :span="7" :offset="1" align="center">标签体系</el-col>
                      <el-col :span="9" :offset="1" align="center">分类</el-col>
                    </el-row>
                    <el-row :gutter="20" v-for="(item, index) in editForm.catalogs" :key="index">
                      <el-col :span="7" :offset="1">
                        <el-form-item
                          :prop="'catalogs.' + index + '.catalogClassId'"
                          :rules="[
                            {
                              required: true,
                              message: '标签体系不能为空',
                              trigger: ['blur', 'change']
                            }
                          ]"
                        >
                          <el-select
                            v-model="item.catalogClassId"
                            :disabled="!editable"
                            @change="changeClass($event, index)"
                          >
                            <el-option
                              v-for="catalogClass in catalogClassList"
                              :key="catalogClass.catalogClassId"
                              :label="catalogClass.catalogClassNm"
                              :value="catalogClass.catalogClassId"
                            ></el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="9" :offset="1">
                        <el-form-item
                          :prop="'catalogs.' + index + '.catalogId'"
                          :rules="[
                            {
                              required: true,
                              message: '分类不能为空',
                              trigger: ['blur', 'change']
                            }
                          ]"
                        >
                          <el-cascader
                            v-model="item.catalogId"
                            :options="item.catalogList"
                            :props="props"
                            :key="index"
                            clearable
                            filterable
                            :disabled="!editable"
                          ></el-cascader>
                        </el-form-item>
                      </el-col>
                      <el-col :span="5" :offset="1">
                        <el-button
                          type="primary"
                          icon="el-icon-plus"
                          size="mini"
                          plain
                          circle
                          @click="addRule(index)"
                        ></el-button>
                        <el-button
                          type="primary"
                          icon="el-icon-minus"
                          size="mini"
                          plain
                          circle
                          @click="deleteRule(index)"
                        ></el-button>
                      </el-col>
                    </el-row>
                  </template>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <template v-else>
        <el-row :gutter="20">
          <el-col :span="24">
            <div class="source-item">
              <div class="source-title linear-cyan">标签包</div>
              <div class="source-content">
                <template v-if="tagInfo.packetId.length">
                  {{ showName('packetId') }}
                </template>
                <span v-else>暂无标签包</span>
              </div>
            </div>
          </el-col>
          <el-col :span="24">
            <div class="source-item">
              <div class="source-title linear-blue">应用渠道</div>
              <div class="source-content">
                <template v-if="tagInfo.applicationChannel.length">
                  {{ showName('applicationChannel', 'application_channel') }}
                </template>
                <span v-else>暂无渠道</span>
              </div>
            </div>
          </el-col>
          <el-col :span="24">
            <div class="catalog-item">
              <div class="source-title linear-yellow"><span>标签分类</span></div>
              <div class="source-content">
                <template v-if="editForm.catalogs.length">
                  <ul>
                    <li v-for="item in editForm.catalogs" :key="item.catalogId">{{ item.catalogPath }}</li>
                  </ul>
                </template>
                <span v-else>暂无分类</span>
              </div>
            </div>
          </el-col>
        </el-row>
      </template>
    </div>
    <div class="content-handler" v-if="tagStatus === 50 && !isModify">
      <el-button type="primary" v-if="!editable" @click="editable = true">编辑</el-button>
      <el-button v-if="editable" @click="cancelEdit">取消</el-button>
      <el-button type="primary" v-if="editable" @click="submit">保存</el-button>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    tagId: {
      type: String,
      required: true,
      default: ''
    },
    tagStatus: {
      type: Number,
      default: 50
    },
    isModify: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      editable: false,
      catalogClassList: [],
      packetList: [],
      editForm: {
        packetId: [],
        applicationChannel: [],
        catalogs: []
      },
      props: {
        expandTrigger: 'hover',
        emitPath: false,
        value: 'catalogId',
        label: 'catalogNm',
        children: '_children'
      },
      editFormRules: {
        packetId: [{ required: true, message: '标签包不能为空', trigger: 'change' }]
        // applicationChannel: [{ required: true, message: '应用渠道不能为空', trigger: 'change' }]
      },
      tagInfo: {
        packetId: [],
        catalogs: [],
        applicationChannel: []
      }
    }
  },
  watch: {
    tagId() {
      this.editable = false
      this.getPackets()
    }
  },
  created() {
    this.getCatalogs()
    this.getPackets()
  },
  methods: {
    getCatalogs() {
      this.$ajax({
        url: this.$ajax.setUrl('dcl/dclAssetCatalogClass/list'),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.catalogClassList = data.data
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    getPackets() {
      this.$ajax({
        url: this.$ajax.setUrl('ast/astTagPacket/list'),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.packetList = data.data
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    addRule(index = 0) {
      let item = {
        catalogClassId: '',
        catalogList: [],
        catalogId: ''
      }
      this.editForm.catalogs.splice(index + 1, 0, item)
    },
    deleteRule(index) {
      this.editForm.catalogs.splice(index, 1)
    },
    changeClass(classId, index) {
      this.editForm.catalogs[index].catalogList = []
      if (classId) {
        this.$ajax({
          url: this.$ajax.setUrl(`dcl/dclAssetCatalog/catalogClassId/${classId}`),
          method: 'get',
          params: this.$ajax.setParams()
        }).then(({ data }) => {
          if (data && data.code === '0') {
            var list = this.$utils.arrayToTree(data.data.length ? data.data.slice(1) : data.data, {
              id: 'catalogId',
              pid: 'parentCatalogId',
              mainSort: 'catalogLevel'
            })
            this.editForm.catalogs[index].catalogList = list
            this.$forceUpdate()
          } else {
            this.$message.error(data.data || data.msg)
          }
        })
      }
    },
    getDetail() {
      this.$ajax({
        url: this.$ajax.setUrl(`ast/astTag/getOrgTagChannelPacketInfo/${this.tagId}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.editForm.applicationChannel = data.data.applicationChannel ? data.data.applicationChannel.split(',') : []
          this.editForm.packetId = []
          this.editForm.catalogs = []
          this.tagInfo = {
            applicationChannel: data.data.applicationChannel ? data.data.applicationChannel.split(',') : [],
            packetId: [],
            catalogs: []
          }
          data.data.packetList.forEach(item => {
            this.editForm.packetId.push(item.packetId)
            this.tagInfo.packetId.push(item.packetId)
          })
          data.data.dclAssetCatalogList.forEach(item => {
            this.editForm.catalogs.push({
              catalogClassId: item.catalogClassId,
              catalogId: item.catalogId,
              catalogPath: item.catalogPath
            })
            this.tagInfo.catalogs.push({
              catalogClassId: item.catalogClassId,
              catalogId: item.catalogId,
              catalogPath: item.catalogPath
            })
          })
          this.editForm.catalogs.forEach((item, index) => this.changeClass(item.catalogClassId, index))
        } else {
          this.$message.error(data.data || data.msg)
        }
      })
    },
    submit() {
      this.$refs['editForm'].validate(valid => {
        if (valid) {
          let catalogs = []
          let packets = []
          this.editForm.catalogs.forEach(item =>
            catalogs.push({ catalogClassId: item.catalogClassId, catalogId: item.catalogId })
          )
          this.editForm.packetId.forEach(item => {
            const target = this.packetList.find(packet => packet.packetId === item)
            packets.push({ packetId: item, packetNm: target.packetNm })
          })
          this.loading = true
          this.$ajax({
            url: this.$ajax.setUrl('ast/astTag/updateOrgTagChannelPacketInfo'),
            method: 'post',
            data: this.$ajax.setData({
              applicationChannel: this.editForm.applicationChannel.join(','),
              packetList: packets,
              tagId: this.tagId,
              dclAssetCatalogList: catalogs
            })
          }).then(({ data }) => {
            if (data && data.code === '0') {
              this.$message.success(data.msg)
              this.editable = false
              this.getDetail()
              this.$emit('callback')
            } else {
              this.$message.error(data.data || data.msg)
            }
            this.loading = false
          })
        }
      })
    },
    cancelEdit() {
      this.reset()
      this.editable = false
    },
    clearForm() {
      this.packetList = []
      this.editForm = {
        applicationChannel: [],
        packetId: [],
        catalogs: []
      }
      this.tagInfo = {
        applicationChannel: [],
        packetId: []
      }
      if (this.editable)
        this.$nextTick(() => {
          this.$refs['editForm'].clearValidate()
          this.editable = false
        })
    },
    reset() {
      this.editForm.applicationChannel = this.tagInfo.applicationChannel
      this.editForm.packetId = this.tagInfo.packetId
      this.editForm.catalogs = this.tagInfo.catalogs
      this.editForm.catalogs.forEach((item, index) => this.changeClass(item.catalogClassId, index))
    },
    showName(fieldName, dictName) {
      let target = []
      this.editForm[fieldName].forEach(item => {
        if (dictName) target.push(this.$dict(dictName)[item])
        else {
          let field = this.packetList.find(packet => packet.packetId === item)
          if (field) target.push(field.packetNm)
        }
      })
      return target.join(',')
    },
    showOrderDrawer() {
      this.$refs.tagOrderDrawer.showDrawer()
    }
  }
}
</script>

<style lang="scss">
.info-application {
  .source-item {
    width: 100%;
    height: 45px;
    margin-bottom: 20px;
    box-shadow: #eee 0 0 10px;
    position: relative;
    .el-select .el-input__inner,
    .el-input .el-input__inner {
      font-size: 16px;
      height: 45px;
      line-height: 45px;
      border: 0;
    }
    .el-input-number {
      width: 100%;
      .el-input__inner {
        padding: 0;
        text-align: left;
      }
      .el-input-number__decrease,
      .el-input-number__increase {
        display: none;
      }
    }
  }
  .catalog-item {
    margin-bottom: 20px;
    box-shadow: #eee 0 0 10px;
    position: relative;
    .source-title {
      height: 100%;
      span {
        display: inline-block;
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
      }
    }
    .el-cascader {
      width: 100%;
    }
    .el-textarea__inner {
      border: 0;
    }
    .el-textarea__inner[readonly='readonly'] {
      border: 0;
      padding: 10px 0;
      margin: 0;
    }
  }
  .source-title {
    font-weight: bold;
    width: 150px;
    padding-left: 50px;
    line-height: 45px;
    color: #fff;
    position: absolute;
    &:before {
      width: 10px;
      height: 10px;
      content: '';
      background-color: #eee9ff;
      border: 2px solid #cfc7ee;
      margin-top: -5px;
      position: absolute;
      top: 50%;
      left: 20px;
      border-radius: 50%;
    }
    &:after {
      width: 0;
      height: 0;
      content: '';
      margin-top: -10px;
      border-top: 10px solid transparent;
      border-bottom: 10px solid transparent;
      position: absolute;
      top: 50%;
      right: -10px;
    }
    &.linear-purpose:after {
      border-left: 10px solid #7c6bed;
    }
    &.linear-blue:after {
      border-left: 10px solid #635fd7;
    }
    &.linear-cyan:after {
      border-left: 10px solid #0696ec;
    }
    &.linear-yellow:after {
      border-left: 10px solid #f19849;
    }
    &.linear-green:after {
      border-left: 10px solid #36b999;
    }
  }
  .long-title {
    padding-left: 40px;
  }
  .source-content {
    line-height: 45px;
    padding: 0 30px 0 180px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    &.rela-content {
      padding-left: 195px;
    }
  }
  .el-input.is-disabled .el-input__inner {
    color: #000;
    background-color: #fff;
  }
  .el-tag.el-tag--info {
    font-size: 16px;
    color: #000;
  }
}
</style>
